package com.dxt.rabbitmq.service.callback;

import com.dxt.rabbitmq.config.ConfirmAndReturnConfig;
import com.dxt.rabbitmq.vo.TestMessage;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ConfirmAndReturnPublisher {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void publish(TestMessage testMessage){
        //设置消息确认，自动调用此函数。消息发送到交换机后，b=true
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            // correlationData 关联数据
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                if (b) {
                    System.out.println("s：" + s);
                    System.out.println("msg send exchange success.");
                } else {
                    System.out.println("msg send exchange faild.");
                }
            }
        });
        //设置消息返回，当消息没有发送到queue中时，会自动调用此方法
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                System.out.println("ReturnedMessage: " + returnedMessage);
            }
        });
        System.out.println("ConfirmAndReturnPublisher send msg ...");
        rabbitTemplate.convertAndSend(ConfirmAndReturnConfig.EXCHANGE, ConfirmAndReturnConfig.ROUTING_KEY, testMessage);
//        rabbitTemplate.convertAndSend(ConfirmAndReturnConfig.EXCHANGE, "routing.key", testMessage);
    }
}
